package com.base.service.workflow.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.base.core.framework.sql.service.impl.SqlBaseServiceImplV1Ext;
import com.base.core.head.constants.CodeResVal;
import com.base.service.workflow.bo.AssignmentStatusEnum;
import com.base.service.workflow.dao.TransferDao;
import com.base.service.workflow.entity.AssignmentDO;
import com.base.service.workflow.entity.FlowDO;
import com.base.service.workflow.entity.TransferDO;
import com.base.service.workflow.service.AssignmentService;
import com.base.service.workflow.service.FlowService;
import com.base.service.workflow.service.TransferService;
import com.gitee.magic.framework.head.exception.BusinessException;

/**
 * @author start 
 * @date 2022-03-29 13:57:28
 */
@Service("transferService")
public class TransferServiceImpl extends SqlBaseServiceImplV1Ext<TransferDO,Long> 
implements TransferService {

	@SuppressWarnings("unused")
	private final TransferDao transferDao;
	@Autowired
	private FlowService flowService;
	@Autowired
	private AssignmentService assignmentService;
	
	public TransferServiceImpl(@Qualifier("transferDao")TransferDao transferDao) {
		super(transferDao);
		this.transferDao=transferDao;
	}
	
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void transfer(Long assignmentId,Long userId,String description) {
		AssignmentDO assignment = assignmentService.load(assignmentId);
		if(assignment.getStatus()!=AssignmentStatusEnum.PENDING) {
			throw new BusinessException(CodeResVal.CODE_10061);
		}
		FlowDO currentFlow = flowService.load(assignment.getFlowId());
		if (currentFlow.getFinished()!=0L) {
			throw new BusinessException(CodeResVal.CODE_10062);
		}
		assignmentService.processed(assignmentId, AssignmentStatusEnum.TRANSFER, description);
		
		AssignmentDO nextAssignment = new AssignmentDO();
		nextAssignment.setFlowId(assignment.getFlowId());
		nextAssignment.setProcessId(assignment.getProcessId());
		nextAssignment.setUserId(userId);
		nextAssignment.setStatus(AssignmentStatusEnum.PENDING);
		assignmentService.save(nextAssignment);
		
		TransferDO transfer=new TransferDO();
		transfer.setFormAssignmentId(assignmentId);
		transfer.setToAssignmentId(nextAssignment.getId());
		transfer.setUserId(userId);
		save(transfer);
	}

}
